package com.sky.interceptor;

import com.alibaba.fastjson.JSON;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.exception.UserNotLoginException;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {
    @Autowired
    JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获得token
        String token = request.getHeader(jwtProperties.getUserTokenName());

        //解析jwt
        try {
            log.info("jwt解析{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            String openid = claims.get(JwtClaimsConstant.USER_ID).toString();
            log.info("当前客户的唯一id为{}", openid);
            //将唯一id放入线程中备用
            BaseContext.setCurrentId(Long.parseLong(openid));
            return true;

        } catch (Exception e) {
            e.printStackTrace();
            //4、不通过，响应401状态码
            response.setStatus(401);
            return false;
        }


    }

}
